package com.firemoss.magicbus.event
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.utils.getQualifiedClassName;
	
	import mx.events.DynamicEvent;
	
	public class DefaultMessagingEventMediator implements IMessagingEventMediator
	{
		public var dispatcher : IEventDispatcher
		
		public function DefaultMessagingEventMediator( eventDispatcher : IEventDispatcher )
		{
			dispatcher = eventDispatcher
		}

		public function createAndDispatch(eventName:String, body:*, bodyPropertyName:String=null, additionalProperties : Object = null, eventClass : Class = null) : void
		{
			var e : Event = createEventFromClass( eventName, eventClass )
			
			if ( additionalProperties )
			{
				for ( var key : String in additionalProperties )
				{
					if( e is DynamicEvent || e.hasOwnProperty( key ) )
					{
						e[ key ] = additionalProperties[ key ]
					}
					else
					{
						trace( "MagicBus cannot set the additional property " + key + " on event of type " + eventName + " and class " + getQualifiedClassName( e ) + ". Check the additionalProperties and ensure that the event class has matching public properties." );
					}
				}
			}

			// Like-named result value overwrites add'l props
			if ( bodyPropertyName && ( e is DynamicEvent || e.hasOwnProperty( bodyPropertyName ) ) )
			{
				e[ bodyPropertyName ] = body
			}
			else
			{
				trace( "MagicBus cannot set the property " + bodyPropertyName + " on event of type " + eventName + " and class " + getQualifiedClassName( e ) + ". If this is a problem, check your resultEventProperty and ensure that the event class has a matching public property." );
			}
			
			dispatcher.dispatchEvent( e )
			
			trace("sending: " + e.type)
		}
		
		private function createEventFromClass( eventName : String, eventClass : Class = null ) : Event
		{
			return ( eventClass ? new eventClass( eventName ) : new DynamicEvent( eventName ) );
		}
		
	}
}